﻿using D.Wx.Dtos;
using D.Wx.Entities;
using FreeSql;

namespace D.Wx.IRepository
{
    public class SysUserGroupRepository : ISysUserGroupRepository
    {
        private readonly IUnitOfWork _uow;
        private readonly IFreeSql _freeSql;
        public SysUserGroupRepository(IFreeSql freeSql, IUnitOfWork uow)
        {
            _freeSql = freeSql;
            _uow = uow;
        }
        public async Task<int> Add(SysUserGroupEntity model)
        {
            return await _freeSql.Insert<SysUserGroupEntity>(model).ExecuteAffrowsAsync();

        }


        public async Task<PageModel<SysUserGroupEntity>> QueryPage(PageQuery pageQuery)
        {
            var sqlQuery = _freeSql.Select<SysUserGroupEntity>()
                               .Where(m => !m.DeleteFlag)
                               .OrderByDescending(m => m.CreateTime);

            var totalCount = await sqlQuery.CountAsync();
            return new PageModel<SysUserGroupEntity>()
            {
                PageNo = pageQuery.Current.Value,
                PageSize = pageQuery.PageSize.Value,
                TotalCount = totalCount,
                TotalPage = (totalCount + pageQuery.PageSize.Value - 1) / pageQuery.PageSize.Value,
                Data = await sqlQuery.Page(pageQuery.Current.Value, pageQuery.PageSize.Value).ToListAsync<SysUserGroupEntity>()
            };
        }

        public async Task<int> Delete(List<string> ids)
        {

            return await _freeSql.Delete<SysUserGroupEntity>().Where(m => ids.Contains(m.Id)).ExecuteAffrowsAsync();

        }
        public async Task<int> Update(SysUserGroupEntity model)
        {
            return await _freeSql.Update<SysUserGroupEntity>().SetSource(model).ExecuteAffrowsAsync();
        }

        public async Task<SysUserGroupEntity> Get(string id)
        {
            return await _freeSql.Select<SysUserGroupEntity>().Where(m => m.Id == id).FirstAsync();
        }

        public async Task<bool> Exists(string name)
        {
            return await _freeSql.Select<SysUserGroupEntity>().Where(m => m.Name == name && !m.DeleteFlag).AnyAsync();
        }

        public async Task<List<SysUserGroupEntity>> GetList()
        {
            return await _freeSql.Select<SysUserGroupEntity>().ToListAsync();
        }
    }
}
